from rest_framework import serializers

from user_info.models import User
from utils.common.base_response import APIResponse


class RegisterSerializer(serializers.Serializer):
    username = serializers.CharField(required=True, error_messages={"required": "用户名必填"})
    password = serializers.CharField(max_length=20, min_length=6)
    re_password = serializers.CharField(max_length=20, min_length=6)

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        re_password = attrs.get('re_password')
        if username:
            user = User.objects.filter(username=username).first()
            if user:
                raise serializers.ValidationError("用户已经存在")
            else:
                if password != re_password:
                    raise serializers.ValidationError("两次密码输入不一致")
                else:
                    attrs['username'] = username
                    attrs['password'] = password
        else:
            raise serializers.ValidationError("请输入用户户名")

        return attrs


class LoginSerializer(serializers.Serializer):
    password = serializers.CharField(max_length=20, min_length=6)
    username = serializers.CharField(max_length=20, min_length=6)
    re_password = serializers.CharField(max_length=20, min_length=6)

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        re_password = attrs.get('re_password')
        if username and password:
            if password == re_password:
                user = User.objects.filter(username=username, password=password).first()
                if not user:
                    raise serializers.ValidationError("用户不存在")
                else:
                    attrs['user'] = user
            else:
                raise serializers.ValidationError("两次密码输入不一致")
        else:
            raise serializers.ValidationError("请输入正确的用户名跟跟密码")
        return attrs


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'email', 'first_name', 'last_name']
